import {WeaTable} from 'comsRedux';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import PropTypes from 'react-router/lib/PropTypes'
import {
    WeaTop,
    WeaTab,
    WeaLeftTree,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
	WeaPopoverHrm,
	WeaErrorPage,
	WeaTools
} from 'ecCom'
import {
	Button, Form, Modal
}
from 'antd'
import Immutable from 'immutable'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'

import CoworkConstant from '../constants/CoworkConstant';
import * as ItemMonitorApis from '../apis/itemMonitor';
import * as ItemMonitorAction from '../actions/itemMonitor'

const confirm = Modal.confirm;
const is = Immutable.is;
const createForm = Form.create;
const FormItem = Form.Item;
const WeaTableAction = WeaTable.action;

/**
 * 主题监控
 */
class ItemMonitor extends React.Component {
	constructor(props) {
		super(props);
	}
	componentDidMount() {
		const { actions } = this.props;

        // 初始化高级搜索区域
        actions.initConditionDatas();
        // 初始化列表
		actions.doTableLoading();
		// 初始化左侧树
		actions.loadLeftTree();
	}
	componentWillReceiveProps(nextProps) {
		return 
			!is(this.props.loading,nextProps.loading) ||
			!is(this.props.comsWeaTable,nextProps.comsWeaTable) ||
			!is(this.props.treeDatas,nextProps.treeDatas) ||
			!is(this.props.treeCounts,nextProps.treeCounts) ||
			!is(this.props.selectedTreeKeys,nextProps.selectedTreeKeys) ||
			!is(this.props.dataKey,nextProps.sessionkey) ||
			!is(this.props.showSearchAd,nextProps.showSearchAd) ||
			!is(this.props.conditioninfo,nextProps.conditioninfo) ||
			!is(this.props.fields,nextProps.fields) ||
			!is(this.props.searchParams, nextProps.searchParams) ||
			!is(this.props.topTab,nextProps.topTab) ||
			!is(this.props.selectedKey, nextProps.selectedKey)
    }
    componentWillUnmount() {
		//组件卸载时一般清理一些状态
		const { actions } = this.props;

		let selectedKey = 'all';
		actions.setSelectedKey(selectedKey);
		actions.setSelectedTreeKeys();
		actions.saveSearchParamsFields();
    }
	render() {
		const { loading, title, actions, topTab, selectedTreeKeys, selectedKey, conditioninfo, showSearchAd, fields, searchParamsAd, sessionkey } = this.props;
		return (
            <div className="wea-cowork-itemMonitor">
				<WeaRightMenu datas={ this.getRightMenu() } onClick={ this.onRightMenuClick.bind(this) }>
					<WeaTop
						title="主题监控"
						loading={ loading }
						icon={ CoworkConstant.icon }
						iconBgcolor={ CoworkConstant.iconBgColor }
						buttonSpace={ 10 }
						showDropIcon={ true }
						dropMenuDatas={ this.getRightMenu() }
						onDropMenuClick={ this.onRightMenuClick.bind(this) }
						buttons={ this.getTopButtons() }
					>
						<WeaLeftRightLayout defaultShowLeft={ false } leftCom={this.getLeftTree()} leftWidth={25}>
							<WeaTab
								datas={ topTab }
								keyParam="groupid"
								onChange={ this.changeTab.bind(this) }
								selectedKey={ selectedKey }

								searchType={['base','advanced']}
								searchsBaseValue={ searchParamsAd.name }
								setShowSearchAd={ bool => { actions.setShowSearchAd(bool) } }
								showSearchAd={ showSearchAd }
								hideSearchAd={ () => actions.setShowSearchAd(false) }
								searchsAd={ <Form horizontal>{this.getSearchs()}</Form> }
								buttonsAd={ this.getTabButtonsAd() }
								onSearch={ v => {actions.doTableLoading()} }
								onSearchChange={ v => { actions.saveSearchParamsFields({name: {name: "name", value: v}}) } }
							/>
							<WeaTable 
								loading={ loading }
								sessionkey={ sessionkey } 
								hasOrder={ true } 
								needScroll={ false }
								getColumns={ this.getNewColumns }
								onOperatesClick={this.onOperatesClick.bind(this)}
							/>
						</WeaLeftRightLayout>
                	</WeaTop>
				</WeaRightMenu>
            </div>
		);
	}

	// 左侧树
	getLeftTree() {
		const { selectedTreeKeys, treeDatas, treeTypes, treeCounts, actions, fields} = this.props;
		return (
			<WeaLeftTree
                datas={ treeDatas }
                counts={ treeCounts }
                countsType={ treeTypes }
                selectedKeys={ selectedTreeKeys }
                onFliterAll={ () => {
                	actions.setSelectedTreeKeys();
                    actions.saveSearchParamsFields();
                    actions.doTableLoading();
                }}
				onSelect={ (treeKey, topTabCount, treeNode) => {
                	//console.info('treeKey',treeKey,'topTabCount',topTabCount,'treeNode',treeNode);
					if(treeKey.indexOf("cMainType_") != -1) {
						// 类别
						actions.saveSearchParamsFields();
					} else if(treeKey.indexOf("cType_") != -1) {
						// 板块
						let key = treeKey.substring(treeKey.indexOf("_") + 1);
						actions.saveSearchParamsFields({typeid: {name: "typeid", value: key}}); //设置高级查询条件的板块条件
					}

					actions.setSelectedTreeKeys([treeKey]);
					
                	actions.setShowSearchAd(false);
					actions.doTableLoading();
                }}
            />
		)
	}

	// 切换tab事件
	changeTab(theKey) {
		const { actions } = this.props;

		actions.setSelectedKey(theKey)
		//actions.setSelectedTreeKeys();
		actions.saveSearchParamsFields();

		this.executeSearch();
	}

	// top中的按钮
	getTopButtons() {
		const { tabkey, sessionkey, comsWeaTable} = this.props;
		let _disabled = !this.getTableSelectedValues().length;
		return [
				(<Button type="primary" disabled={_disabled} onClick={this.batchCoworkItemMonitorDel.bind(this)}>批量删除</Button>),
				(<Button type="primary" disabled={_disabled} onClick={this.batchCoworkItemMonitorEnd.bind(this)}>批量结束</Button>),
				(<Button type="primary" disabled={_disabled} onClick={this.setTop.bind(this)}>标记置顶</Button>),
				(<Button type="primary" disabled={_disabled} onClick={this.cancelTop.bind(this)}>取消置顶</Button>)
			];
	}
	// 右键菜单
    getRightMenu() {
		const { tabkey, sessionkey, comsWeaTable} = this.props;
		let _disabled = !this.getTableSelectedValues().length;

		let btns = [];
		btns.push({ key: "search", icon: <i className='icon-coms-search'/>, content: '搜索' });
		
		btns.push({ key: "batchCoworkItemMonitorDel", icon: <i className='icon-coms-Custom'/>, content: '批量删除', disabled:_disabled });
		btns.push({ key: "batchCoworkItemMonitorEnd", icon: <i className='icon-coms-Custom'/>, content: '批量结束', disabled:_disabled });
		btns.push({ key: "setTop", icon: <i className='icon-coms-Custom'/>, content: '标记置顶', disabled:_disabled });
		btns.push({ key: "cancelTop", icon: <i className='icon-coms-Custom'/>, content: '取消置顶', disabled:_disabled });

		btns.push({ key: "ShowCustomColumns", icon: <i className='icon-coms-Custom'/>, content: '显示定制列' });
		/*
		btns.push({ key: "collection", icon: <i className='icon-coms-Custom'/>, content: '收藏' });
		btns.push({ key: "help", icon: <i className='icon-coms-Custom'/>, content: '帮助' });
		*/
        return btns;
	}
	//右键菜单事件绑定
    onRightMenuClick(key) {
		const { actions, sessionkey } = this.props;
		if (key == "search") {
			this.executeSearch();
		} 
		else if (key == "batchCoworkItemMonitorDel") {
			this.batchCoworkItemMonitorDel();
		} 
		else if (key == "batchCoworkItemMonitorEnd") {
			this.batchCoworkItemMonitorEnd();
		} 
		else if (key == "setTop") {
			this.setTop();
		} 
		else if (key == "cancelTop") {
			this.cancelTop();
		} 	
		else if (key == "ShowCustomColumns") {
			actions.setColSetVisible(sessionkey, true);
			actions.tableColSet(sessionkey, true);
		} 
	}

	// 执行搜索方法（也可用于刷新table）
	executeSearch() {
		const { actions } = this.props;
		actions.setShowSearchAd(false);
		actions.doTableLoading();
	}

	batchCoworkItemMonitorDel() {
		this.executeButtonMethod('batchCoworkItemMonitorDel');
	}
	batchCoworkItemMonitorEnd() {
		this.executeButtonMethod('batchCoworkItemMonitorEnd');
	}
	setTop() {
		this.executeButtonMethod('setTop');
	}
	cancelTop() {
		this.executeButtonMethod('cancelTop');
	}
	executeButtonMethod(type, values) {
		//console.info("executeButtonMethod", this.props, type, values);
		const { actions } = this.props;
		if(!values) {
			values = this.getTableSelectedValues();
		}
		let reloadTable = this.executeSearch.bind(this);

		switch(type) {
			case "batchCoworkItemMonitorDel" : 
				{
					confirm({
						title: '确定删除选定的信息吗？',
						content: '',
						onOk() {
							actions.batchCoworkItemMonitorDel({
								coworkids: values
							});
							reloadTable();
						},
						onCancel() {},
					});
				}
				break;
			case "batchCoworkItemMonitorEnd" : 
				{
					confirm({
						title: '确定要结束选择的协作？',
						content: '',
						onOk() {
							actions.batchCoworkItemMonitorEnd({
								coworkids: values
							});
							reloadTable();
						},
						onCancel() {}
					});
				}
				break;
			case "setTop" : 
				{
					actions.batchCoworkItemMonitorTop({
						coworkids: values
					});
					reloadTable();
				}
				break;
			case "cancelTop" : 
				{
					actions.batchCoworkItemMonitorCancelTop({
						coworkids: values
					});
					reloadTable();
				}
				break;
		}
	}

	// 获得table选中行的主键值数组。若没选中任何一条，返回空数组
	getTableSelectedValues() {
		const { tabkey, sessionkey, comsWeaTable} = this.props;
		const moudleTablekey = sessionkey ? sessionkey.split('_')[0] : 'init';
		const moudleTableNow = comsWeaTable.get(moudleTablekey);
		const moudleSelectedRowKeys = moudleTableNow.get('selectedRowKeys');
		let values = moudleSelectedRowKeys.toJS();
		return values;
	}

	//高级搜索group定义
    getSearchs() {
        return [
            (<WeaSearchGroup needTigger={true} title={this.getTitle()} showGroup={this.isShowFields()} items={this.getFields()}/>)
        ]
	}
	//高级搜索分组标题
	getTitle(index = 0) {
        const {conditioninfo} = this.props;
        return !isEmpty(conditioninfo) && conditioninfo[index].title
	}
	//高级搜索分组是否展示
    isShowFields(index = 0) {
        const {conditioninfo} = this.props;
        if(conditioninfo.length == 0){
            return true;
        }
        return !isEmpty(conditioninfo) && conditioninfo[index].defaultshow
    }
    // 0 常用条件，1 其他条件
    getFields(index = 0) {
        const {conditioninfo} = this.props;
        const fieldsData = !isEmpty(conditioninfo) && conditioninfo[index].items;
		let items = [];
        fieldsData && fieldsData.forEach( (field) => {
            items.push({
				com:(
					<FormItem
						label={`${field.label}`}
						labelCol={{span: `${field.labelcol}`}}
						wrapperCol={{span: `${field.fieldcol}`}}>
                    {WeaTools.getComponent(field.conditionType, field.browserConditionParam, field.domkey, this.props,field)}
                    </FormItem>),
                colSpan:1
			});
        });
        return items;
    }
	//高级搜索底部按钮定义
    getTabButtonsAd() {
        const { actions } = this.props;
        return [
            (<Button type="primary" onClick={ () => { actions.setShowSearchAd(false); actions.doTableLoading();} }>搜索</Button>),
            (<Button type="ghost" onClick={ () =>{ actions.saveSearchParamsFields() } }>重置</Button>),
            (<Button type="ghost" onClick={ () => {actions.setShowSearchAd(false) } }>取消</Button>)
        ]
	}

	//自定义过滤渲染
	getNewColumns(columns) {
        let newColumns = '';
        newColumns = columns.map(column => {
                let newColumn = column;
				newColumn.render = (text, record, index) => { //前端元素转义
                    let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
                    let url = '';
					if(newColumn.dataIndex == 'name') {
						url = '/cowork/ViewCoWork.jsp?id=' + record.id;
					}
                    return(
						url == '' ?
							<div className="wea-url" dangerouslySetInnerHTML={{__html: valueSpan}} />
						:
							<div className="wea-url-name" dangerouslySetInnerHTML={{__html: valueSpan}} style={{cursor:'pointer'}} title={text} onClick={()=>{window.open(url)}} />
                    )
                }
                return newColumn;
			});
		return columns;
	}

	//表格单元格转义
	onOperatesClick = (record, index, operate, flag) => {
		const { searchParamsAd } = this.props;
		//console.info("onOperatesClick", record, index, operate, flag);
		let coworkId = record.id;
		if(flag == 0) { //删除
			this.executeButtonMethod("batchCoworkItemMonitorDel", coworkId);
		} else if(flag == 1) { //结束
			this.executeButtonMethod("batchCoworkItemMonitorEnd", coworkId);
		} else if(flag == 2) { //置顶
			this.executeButtonMethod("setTop", coworkId);
		} else if(flag == 3) { //取消置顶
			this.executeButtonMethod("cancelTop", coworkId);
		}
	}
}


// form 表单与 redux 双向绑定
ItemMonitor = Form.create({
	onFieldsChange(props, fields) {
		props.actions.saveSearchParamsFields({...props.fields, ...fields});
	}, 
	mapPropsToFields(props) {
		return props.fields;
	}
})(ItemMonitor);

//组件检错机制
class MyErrorHandler extends React.Component {
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== "";
		return(
			<WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
		);
	}
}
ItemMonitor = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(ItemMonitor);

// 把 state map 到组件的 props 上
const mapStateToProps = state => {
	const { loading, title, actions, topTab, selectedTreeKeys, treeDatas, treeTypes, treeCounts, selectedKey, conditioninfo, showSearchAd, fields, searchParamsAd, sessionkey } = state.coworkItemMonitor;
	const { comsWeaTable } = state;
	return { loading, title, actions, topTab, selectedTreeKeys, treeDatas, treeTypes, treeCounts, selectedKey, conditioninfo, showSearchAd,  fields, searchParamsAd, sessionkey, comsWeaTable };
	
}
// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
    return {
        actions: bindActionCreators({...ItemMonitorAction, ...WeaTableAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ItemMonitor);
